package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study1.dopost;

import cn.hutool.json.JSONObject;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TestPost {
    /**
     * 表单类型application/x-www-form-urlencoded
     * @throws Exception
     */
    @Test
    public void testPost1() throws Exception{
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        urlStr = "http://localhost:8899/httpclient-demo/test";
        // 构造httpPost请求对象
        HttpPost httpPost = new HttpPost(urlStr);
        // 设置请求头
        httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");

        // 给post对象设置参数
        List<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("userName","aa"));
        list.add(new BasicNameValuePair("password","abc"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,StandardCharsets.UTF_8);
        httpPost.setEntity(formEntity);
        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            // 获取响应头
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
                System.out.println("响应头名字"+allHeader.getName()+"值："+allHeader.getValue());
            }
            // 代表本次请求的成功，失败的状态
            StatusLine statusLine = response.getStatusLine();
            if(HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("响应成功");
                // 获取响应结果
                HttpEntity entity = response.getEntity();
                // contentType的值
                Header contentType = entity.getContentType();
                // 对httpEntity操作的工具类
                String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStr);
                // 确保
                EntityUtils.consume(entity);
            }else {
                System.out.println("响应失败"+statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }
    /**
     * json类型  application/json
     * @throws Exception
     */
    @Test
    public void testPost2() throws Exception{
        // 可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlStr = "https://www.baidu.com/";
        urlStr = "http://localhost:8899/httpclient-demo/test";
        // 构造httpPost请求对象
        HttpPost httpPost = new HttpPost(urlStr);
        // string是一个json字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName","agc");
        jsonObject.put("password","123");
        // 给post对象设置参数
        StringEntity jsonEntity = new StringEntity(jsonObject.toString(),StandardCharsets.UTF_8);
        jsonEntity.setContentType("application/json; charset=utf-8");

//        jsonEntity.setContentType(new BasicHeader("Content-Type","application/json; charset=utf-8"));
        // 设置entity编码
        jsonEntity.setContentEncoding(Consts.UTF_8.name());

        httpPost.setEntity(jsonEntity);
        // 响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            // 获取响应头
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
                System.out.println("响应头名字"+allHeader.getName()+"值："+allHeader.getValue());
            }
            // 代表本次请求的成功，失败的状态
            StatusLine statusLine = response.getStatusLine();
            if(HttpStatus.SC_OK == statusLine.getStatusCode()) {
                System.out.println("响应成功");
                // 获取响应结果
                HttpEntity entity = response.getEntity();
                // contentType的值
                Header contentType = entity.getContentType();
                // 对httpEntity操作的工具类
                String toStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStr);
                // 确保
                EntityUtils.consume(entity);
            }else {
                System.out.println("响应失败"+statusLine.getStatusCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if(response != null) {
                response.close();
            }
        }
    }

}
